import requests
from lxml import etree
import re

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',
}


# 历史今日数据
def historical_today(tree):
    data = []
    for i in range(8):
        date = tree.xpath(f'/html/body/div[3]/div[3]/div/div[5]/div/div[1]/div[1]/p[{i + 1}]/text()')[0]
        maxtmp = tree.xpath(f'/html/body/div[3]/div[3]/div/div[5]/div/div[1]/div[2]/p[{i + 1}]/text()')[0]
        mintmp = tree.xpath(f'/html/body/div[3]/div[3]/div/div[5]/div/div[1]/div[3]/p[{i + 1}]/text()')[0]
        avgtmp = tree.xpath(f'/html/body/div[3]/div[3]/div/div[5]/div/div[1]/div[4]/p[{i + 1}]/text()')[0]
        pcpn = tree.xpath(f'/html/body/div[3]/div[3]/div/div[5]/div/div[1]/div[5]/p[{i + 1}]/text()')[0]
        obj = {
            'date': date,
            'maxtmp': maxtmp,
            'mintmp': mintmp,
            'avgtmp': avgtmp,
            'pcpn': pcpn
        }
        data.append(obj)
    return data


# 昨天数据
def historical_yesterday(text):
    yesterday = re.findall('window.yesterdayData = (.*?);', text)[0]
    data_list = re.findall('"maxTmp":(.*?),"minTmp":(.*?),"avgTmp":(.*?),"hum":(.*?),"wind":(.*?),"aqi":(.*?),"qlty":"(.*?)"',yesterday)[0]
    data = {
        'maxTmp': data_list[0],
        'minTmp': data_list[1],
        'avgTmp': data_list[2],
        'hum': data_list[3],
        'wind': data_list[4],
        'aqi': data_list[5],
        'qlty': data_list[6],
    }
    return data


# 历史月度温度统计
def historical_statsByMonth(text):
    statsByMonth = re.findall('window.statsByMonth = (.*?);', text)[0]
    # 双层嵌套
    legend = re.findall('"(.*?)"', re.findall('"legend":\[(.*?)]', statsByMonth)[0])
    maxTmp = re.findall('"maxTmp":\[(.*?)]', statsByMonth)[0].split(',')
    minTmp = re.findall('"minTmp":\[(.*?)]', statsByMonth)[0].split(',')
    avgTmp = re.findall('"(.*?)"', re.findall('"avgTmp":\[(.*?)]', statsByMonth)[0])

    data = {
        'legend': legend,
        'maxTmp': maxTmp,
        'minTmp': minTmp,
        'avgTmp': avgTmp,
    }
    return data


# 历史降水量
def historical_rain(text):
    rain = re.findall('window.rainDayData = (.*?);', text)[0]

    legend = re.findall('"(.*?)"', re.findall('"legend":\[(.*?)]', rain)[0])
    days = re.findall('"(.*?)"', re.findall('"days":\[(.*?)]', rain)[0])
    pcpn = re.findall('"(.*?)"', re.findall('"pcpn":\[(.*?)]', rain)[0])

    data = {
        'legend': legend,
        'days': days,
        'pcpn': pcpn
    }
    return data


# 历史降水量
def historical_hum(text):
    humData = re.findall('window.humData = (.*?);', text)[0]

    legend = re.findall('"(.*?)"', re.findall('"legend":\[(.*?)]', humData)[0])
    hum = re.findall('"hum":\[(.*?)]', humData)[0].split(',')
    data = {
        'legend': legend,
        'hum': hum,
    }
    return data


# 历史数据
def historicalHtml(city, code):
    weather_url = f'https://www.qweather.com/historical/{city}-{str(code)}.html'
    try:
        response = requests.get(url=weather_url, headers=headers)
        weather_tree = etree.HTML(response.text)

        historicalToday = historical_today(weather_tree)
        historicalYesterday = historical_yesterday(response.text)
        historicalStatsByMonth = historical_statsByMonth(response.text)
        historicalRain = historical_rain(response.text)
        historicalHum = historical_hum(response.text)
        data = {
            'historicalToday': historicalToday,
            'historicalYesterday': historicalYesterday,
            'historicalStatsByMonth': historicalStatsByMonth,
            'historicalRain': historicalRain,
            'historicalHum': historicalHum
        }
        # print(data)
        return data
    except:
        string = '爬取失敗,请检查输入的参数是否正确'
        print(string)
        return string


# 测试代码
# historicalHtml('guangzhou', 101280101)